package de.rj.urwalking.loader;

import java.util.ArrayList;

import android.content.Context;
import android.location.Location;
import android.util.Log;

import com.threed.jpct.SimpleVector;

import de.ralf.urwalking.soplugin.EPSGPoint;
import de.rj.urwalking.data.Poi;
import de.rj.urwalking.db.ReadWritePostgreSQL;
import de.rj.urwalking.util.GeoUtil;
import de.rj.urwalking.util.PrefUtil;

/**
 * Used to load the POIs in a separate thread.
 * @author rjj
 *
 */

public class PoiLoader extends AsyncLoader<ArrayList<Poi>> {
	
	private SimpleVector offset;
	private Context context;
	
	/** EPSG31468-Hochwert*/
	private double northing;
	/** EPSG31468-Rechtswert*/
	private double easting;

	public PoiLoader(Context context, SimpleVector offset, Location location) {
		super(context);
		this.context = context;
		this.offset = offset;

		// convert GPS coordinates to EPSG 31468, which is used in the database
		EPSGPoint epsgPoint = GeoUtil.convertLatLonToEPSG31468(location.getLongitude(), location.getLatitude());
		northing = epsgPoint.getY();
		easting = epsgPoint.getX();
	}

	public PoiLoader(Context context, SimpleVector offset, SimpleVector cameraPosition) {

		super(context);
		this.context = context;
		this.offset = offset;

		northing = offset.y + cameraPosition.y;
		easting = offset.x + cameraPosition.x;

	}

	@Override
	public ArrayList<Poi> loadInBackground() {

		// connect to database
		ReadWritePostgreSQL dbWrapper = new ReadWritePostgreSQL();
		
		// read the radius from preferences
		double radius = PrefUtil.readRadius(context);
		
		// load POIs in this radius around the current position
		ArrayList<Poi> pois = dbWrapper.getPOIsWithinRadius(easting, northing, radius);

		dbWrapper.closeConnection();

		// prepare the POIs for display
		for (int i = 0; i < pois.size(); i++) {
			pois.get(i).applyOffset(offset);
			pois.get(i).setIcon(context);
		}

		return pois;
	}

}
